//
//  ToolHelper.m
//  StoneMason
//
//  Created by iOS1 on 16/12/28.
//  Copyright © 2016年 iOS1. All rights reserved.
//

#import "ToolHelper.h"
#import <CoreTelephony/CTCarrier.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import "sys/utsname.h"

#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>

@implementation ToolHelper

+(instancetype)shareInstance{
    static ToolHelper *toolHelper = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        toolHelper = [[ToolHelper alloc] init];
    });
    return toolHelper;
}

+(NSDate *)chageTimeStrToDate:(NSString *)dateStr withFormater:(NSString *)format{
    NSDateFormatter *formater = [[NSDateFormatter alloc] init];
    [formater setDateFormat:format];
    NSDate *date = [formater dateFromString:dateStr];
    return date;
}

+(NSString *)showProvinceCityCounty:(NSString *)province withCity:(NSString *)city withCounty:(NSString *)area withFormat:(NSString *)format{
    if (province.length >= 3) {
        province = [province substringToIndex:2];
    }
    if (city.length >= 3) {
        city = [city substringToIndex:2];
    }
    if (area.length >= 3) {
        area = [area substringToIndex:2];
    }
    if (format.length == 0) {
        format = @"-";
    }
    area = [area isEqual:@"全部"] ? @"" : area;
    NSString *cityStr = [NSString stringWithFormat:@"%@%@%@%@%@",province,format,city,format,area];
    if ([province isEqual:city]) {
        cityStr = [NSString stringWithFormat:@"%@%@%@",province,format,area];
        if(area.length == 0){
            cityStr = [NSString stringWithFormat:@"%@",province];
        }
    }else{
        if(area.length == 0){
            cityStr = [NSString stringWithFormat:@"%@%@%@",province,format,city];
        }
    }
    return cityStr;
}

+(NSString *)changetimeStamp:(NSString *)timeStamp andFormatter:(NSString *)format{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    if (format.length == 0 || format == nil) {
        [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    }else{
        [formatter setDateFormat:format];
    }
    if (timeStamp.length == 13) {
        timeStamp = [NSString stringWithFormat:@"%lld",[timeStamp longLongValue]/1000];
    }
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[timeStamp longLongValue]];
    return [formatter stringFromDate:date];
}

+(BOOL)doesString:(NSString *)string MatchCondition:(NSArray *)conditionstrings {
    for (NSString *condition in conditionstrings) {
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", condition];
        if ([predicate evaluateWithObject:string] == NO) {
            return NO;
        }
    }
    return YES;
}

+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSError *err;
    
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
    
    if(err) {
        
        NSLog(@"json字典解析失败：%@",err);
        
        return nil;
        
    }
    return dic;
}

//字典转json格式字符串：
+ (NSString*)dictionaryToJson:(NSDictionary *)dic {
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    NSString *hasNStr =  [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    NSString *endeStr = [hasNStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    return endeStr;
}

//字符串转数组
+(NSArray *)arrayWithJsonString:(NSString *)jsonString {
    
    if (jsonString == nil) {
        
        return nil;
        
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSError *err;
    
    NSArray *arr = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
    
    if(err) {
        
        NSLog(@"json数组解析失败：%@",err);
        
        return nil;
        
    }
    
    return arr;
}

//数组转json格式字符串：

+(NSString*)arrayTojsonString:(NSArray *)arr {
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:&parseError];
    
    NSString *hasNStr =  [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    NSString *endeStr = [hasNStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    return endeStr;
    
}

+(void)saveUserdefaults
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults synchronize];
}

+(UIColor *) randomColor{
    
    CGFloat hue = ( arc4random() % 256 / 256.0 ); //0.0 to 1.0
    
    CGFloat saturation = ( arc4random() % 128 / 256.0 ) + 0.5; // 0.5 to 1.0,away from white
    
    CGFloat brightness = ( arc4random() % 128 / 256.0 ) + 0.5; //0.5 to 1.0,away from black
    
    return [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1];
}

/**随机数*/

+(int)randomNumber:(int)from to:(int)to {
    return (int)(from + (arc4random() % (to -from + 1)));
}

+(id)userDefaultsForKey:(NSString *)key {
    return [[NSUserDefaults standardUserDefaults]objectForKey:key];
}

+(void)setUserDefault:(id)value forKey:(NSString *)key {
    [[NSUserDefaults standardUserDefaults]setObject:value forKey:key];
    [self saveUserdefaults];
}

/**添加虚线*/
+(void)addDottedWithLayer:(CALayer *)layer {
    CAShapeLayer *border = [CAShapeLayer layer];
    
    border.strokeColor = [UIColor lightGrayColor].CGColor;
    
    border.fillColor = nil;
    
    border.path = [UIBezierPath bezierPathWithRect:layer.bounds].CGPath;
    
    border.frame = layer.bounds;
    
    border.lineWidth = 1.f;
    
    border.lineCap = @"square";
    
    border.lineDashPattern = @[@4, @4];
    
    [layer addSublayer:border];
}

+ (UIImage *)cutScreenView:(UIView *)view {
    CGRect rect = view.frame;
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [view.layer renderInContext:context];
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

+(UIImage *)ImageWithColor:(UIColor *)color {
    CGRect frame = CGRectMake(0, 0, 1, 1);
    UIGraphicsBeginImageContext(frame.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, color.CGColor);
    CGContextFillRect(context,frame);
    
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

+(NSString *)imageInDeffrentSizeNamed:(NSString *)imag {
    NSString *imgStr;
    if ([UIScreen mainScreen].scale == 2) {
        imgStr = [NSString stringWithFormat:@"%@@2x.png",imag];
    }
    else imgStr = [NSString stringWithFormat:@"%@@3x.png",imag];
    
    NSString *bundleStr = [[NSBundle mainBundle]pathForResource:imgStr ofType:nil];
    return bundleStr;
}


+(NSString *)getDocumentWithFileName:(NSString *)filename {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docPathStr = [paths objectAtIndex:0];
    NSString *filePath = [NSString stringWithFormat:@"%@/%@",docPathStr,filename];
    return filePath;
}

+(void)dailContactPhoneWithNoPrompt:(NSString *)phone{
    NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@", phone];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
}

+(void)dailContactPhoneWithPrompt:(NSString *)phone{
    NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"telprompt://%@", phone];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
}

+(void)dailPhoneAlert:(NSString *)phone withVc:(UIViewController *)curVc{
    UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"" message:phone preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    DefineWeakSelf;
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"呼叫" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf dailContactPhoneWithNoPrompt:phone];
    }];
    [alertView addAction:cancleAction];
    [alertView addAction:okAction];
    [curVc presentViewController:alertView animated:YES completion:nil];
}

+(NSString *)currentSystemMillisecond{
    NSDateFormatter *formatter = [[NSDateFormatter alloc ] init];
    [formatter setDateFormat:@"YYYYMMddHHmmsss"];
    NSDate *nowDate = [NSDate date];
    NSString *timeSp = [NSString stringWithFormat:@"%ld",(long)[nowDate timeIntervalSince1970]];
    
    return timeSp;
}

+(void)showAlert:(NSString *)title withVc:(UIViewController *)curVc confirmBlock:(void(^)(void))confirmBlock{
    UIAlertController *alertView = [UIAlertController alertControllerWithTitle:title message:@"" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        confirmBlock();
    }];
    [alertView addAction:cancleAction];
    [alertView addAction:okAction];
    [curVc presentViewController:alertView animated:YES completion:nil];
}

+(void)showAlert:(NSString *)title withMsg:(NSString *)msg cancelBtnTitle:(NSString *)cancleTitle okBtnTitle:(NSString *)okTitle withVc:(UIViewController *)curVc confirmBlock:(void(^)(void))confirmBlock{
    UIAlertController *alertView = [UIAlertController alertControllerWithTitle:title message:msg preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:cancleTitle style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:okTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        confirmBlock();
    }];
    [alertView addAction:cancleAction];
    [alertView addAction:okAction];
    [curVc presentViewController:alertView animated:YES completion:nil];
}

+(void)showAlert:(NSString *)title withMsg:(NSString *)msg cancelBtnTitle:(NSString *)cancleTitle okBtnTitle:(NSString *)okTitle withVc:(UIViewController *)curVc cancelBtnTitleColor:(UIColor *)titleColor confirmBlock:(void(^)(void))confirmBlock{
    UIAlertController *alertView = [UIAlertController alertControllerWithTitle:title message:msg preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:cancleTitle style:UIAlertActionStyleCancel handler:nil];
    [cancelAction setValue:titleColor forKey:@"_titleTextColor"];
    
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:okTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        confirmBlock();
    }];
    [alertView addAction:cancelAction];
    [alertView addAction:okAction];
    [curVc presentViewController:alertView animated:YES completion:nil];
}

+(BOOL)validateStrIsContainSpecialChar:(NSString *)str{
    if ([str rangeOfString:@"&lt;"].location != NSNotFound || [str rangeOfString:@"&gt;"].location != NSNotFound || [str rangeOfString:@"&amp"].location != NSNotFound) {
        return YES;
    }
    return NO;
}

+(void)saveDataToUserDefault:(NSString *)key valueVc:(NSString *)value{
    NSUserDefaults *df = [NSUserDefaults standardUserDefaults];
    [df setObject:value forKey:key];
    [df synchronize];
}

+ (NSString *)getRandomStringWithNum:(NSInteger)num {
    NSString *string = [[NSString alloc]init];
    for (int i = 0; i < num; i++) {
        int number = arc4random() % 36;
        if (number < 10) {
            int figure = arc4random() % 10;
            NSString *tempString = [NSString stringWithFormat:@"%d", figure];
            string = [string stringByAppendingString:tempString];
        }else {
            int figure = (arc4random() % 26) + 97;
            char character = figure;
            NSString *tempString = [NSString stringWithFormat:@"%c", character];
            string = [string stringByAppendingString:tempString];
        }
    }
    return string;
}

// 字典转化为json
+(NSString *)convertToJsonData:(NSDictionary *)dict{
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString;
    if (!jsonData) {
        NSLog(@"%@",error);
    }else{
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    
//    NSRange range = {0,jsonString.length};
    //去掉字符串中的空格
//    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    
//    NSRange range2 = {0,mutStr.length};
//    //去掉字符串中的换行符
//    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    
    return mutStr;
    
}

// image转化成Base64位
+ (NSString *)imageChangeBase64: (UIImage *)image{
    
    NSData   *imageData = nil;
    //NSString *mimeType  = nil;
    if ([self imageHasAlpha:image]) {
        
        imageData = UIImagePNGRepresentation(image);
        //mimeType = @"image/png";
    }else{
        
        imageData = UIImageJPEGRepresentation(image, 0.3f);
        //mimeType = @"image/jpeg";
    }
    return [NSString stringWithFormat:@"data:image/gif;base64,%@",[imageData base64EncodedStringWithOptions: 0]];
}

+ (BOOL)imageHasAlpha:(UIImage *)image{
    
    CGImageAlphaInfo alpha = CGImageGetAlphaInfo(image.CGImage);
    return (alpha == kCGImageAlphaFirst ||
            alpha == kCGImageAlphaLast ||
            alpha == kCGImageAlphaPremultipliedFirst ||
            alpha == kCGImageAlphaPremultipliedLast);
}

+(NSDateComponents *)dateComponent{
    // 获取代表公历的NSCalendar对象
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    // 获取当前日期
    NSDate *dt = [NSDate date];
    unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth |  NSCalendarUnitDay;
    // 获取不同时间字段的信息
    NSDateComponents *comp = [gregorian components:unitFlags fromDate:dt];
    return comp;
}

+(void)addressNavigation:(NSString *)lng lat:(NSString *)lat{
    if ([lat isEqualToString:@""] || [lng isEqualToString:@""]) {
        [self showRequestStatus:@"缺少位置信息不能导航" type:0];
        return;
    }
    //导航界面
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init] ;
    [formatter setNumberStyle: NSNumberFormatterDecimalStyle];
    double lati = [[formatter numberFromString:lat] doubleValue];
    double longti = [[formatter numberFromString:lng] doubleValue];
    CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(lati,longti);
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"iosamap://"]]) {
        NSString *urlsting =[[NSString stringWithFormat:@"iosamap://navi?sourceApplication= &backScheme= &lat=%f&lon=%f&dev=0&style=2",lati,longti] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        [[UIApplication  sharedApplication]openURL:[NSURL URLWithString:urlsting]];
    }else if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"baidumap://"]]){
        NSString *urlsting =[[NSString stringWithFormat:@"baidumap://map/direction?origin={{我的位置}}&destination=latlng:%f,%f|name=目的地&mode=driving&coord_type=gcj02",lati,longti] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlsting]];
    }else {
        MKMapItem *currentLocation =[MKMapItem mapItemForCurrentLocation];
        MKMapItem *toLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:coordinate addressDictionary:nil]];
        [MKMapItem openMapsWithItems:@[currentLocation,toLocation] launchOptions:@{MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeDriving,
                                                                                   MKLaunchOptionsShowsTrafficKey:[NSNumber numberWithBool:YES]}];
    }
}

-(void)dialPhoneAlertView:(UIViewController *)vc phone:(NSString *)phone{
//    CallPhoneAlertView *callView = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([CallPhoneAlertView class]) owner:nil options:nil] lastObject];
//    callView.frame = CGRectMake(0, 0, ScreenWidth, ScreenHight);
//    callView.phoneNumLbl.text = [NSString stringWithFormat:@"%@  (7*24h)", phone];
//    __strong typeof(vc) weakSelf = vc;
//    callView.delegate = weakSelf;
//    [vc.view addSubview:callView];
}

+(void)showRequestStatus:(NSString *)msg type:(NSInteger)status{
    if (![msg isEqual:[NSNull null]]) {
        if(status == 0){
            [SVProgressHUD showErrorWithStatus:msg];
        }else{
            [SVProgressHUD showSuccessWithStatus:msg];
        }
        [SVProgressHUD dismissWithDelay:1.0f];
    }
}

+(void)setShadowWithView:(UIView *)view shadowOffset:(CGSize)size shadowOpacity:(CGFloat)shadowOpacity{
    view.layer.shadowColor = [UIColor colorWithHexString:@"1B1A20"].CGColor;
    view.layer.shadowOpacity = shadowOpacity;
    view.layer.shadowOffset = size;
    view.backgroundColor = [UIColor whiteColor];
}

@end
